#include <stdio.h>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <string.h>

#include "Connection.h"
#include "Account.h"
#include "Session.h"
#include "main.h"

#include <mysql++.h>
#include <Parse.h>

using namespace std;

Connection::Connection(ISocketHandler& h) : TcpSocket(h)
{
    SetLineProtocol();
    session = new Session();
}


Connection::~Connection()
{

}

void Connection::OnAccept()
{
	printf("Accettata richiesta di connessione\n");
}

void Connection::OnLine(const std::string& cmdIn)
{
    cout << "received : " << cmdIn<<endl;
    //parserize del cmd ricevuto
    Parse p = Parse(cmdIn);
    std::string cmd = p.getword();
    cout << "CMD : " << cmd << endl;
    if(cmd == "REGISTRE" )
    {
        if(session->getSessionStatus()==CONNECT){
            Send("REGISTREOK\n");
            //TODO : prevedere l'invio di REGISTREKO se non è consentita la registrazione
            session->setSessionStatus(REGISTRE);
        }
        else {
            Send("REGISTREKO\n");
        }
    }else
    if(cmd == "LOGIN" )
    {
        if(session->getSessionStatus()==CONNECT){
            Send("LOGINOK\n");
            //TODO : prevedere l'invio di LOGINKO se non è consentita la registrazione
            session->setSessionStatus(LOGIN);
        }
        else {
            Send("LOGINKO\n");
        }
    }
    else if((cmd == "LOGINUSER") & (session->getSessionStatus()==LOGIN) )
    {
        Account *account = new Account();
        std::string user = p.getword();
        std::string pwd = p.getword();
        int err = account->login(user,pwd);
        if(err<=LOGIN_OK){
            Send("LOGINUSEROK\n");
            session->setSessionStatus(LOGGED);
        }
        else {
            std::string str = "LOGINUSERKO=";
            str += (int)err+48;
            str += "\n";
            Send(str);
            session->setSessionStatus(LOGIN);
        }
    }
    else if((cmd == "NEWUSER") & (session->getSessionStatus()==REGISTRE) )
    {
        Account *reg = new Account();
        std::string user = p.getword();
        std::string pwd = p.getword();
        std::string mail = p.getword();
        int err = reg->registreNewAccount(user,pwd,mail);
        if(err==REGOK){
            Send("NEWUSEROK\n");
            session->setSessionStatus(CONNECT);
        }
        else {
            std::string str = "NEWUSERKO=";
            str += (int)err+48;
            str += "\n";
            Send(str);
            session->setSessionStatus(REGISTRE);
        }
    }
    else
    if ((cmd == "WELCOME") & (session->getSessionStatus()==LOGGED) )
    {
        mysqlpp::Connection conn(false);

        if (conn.connect(
                    dbSetting->getDb(),
                    dbSetting->getServer(),
                    dbSetting->getUser(),
                    dbSetting->getPass()
                )
            )
        {
            //check Username
            mysqlpp::Query query = conn.query();
            try{
                query << "SELECT TT_VAR_STRING FROM TT_VARIABLE WHERE TT_VAR_NAME = 'WELCOME_MSG'";
                if (mysqlpp::StoreQueryResult res = query.store()){
                    if(res.num_rows()>0){
                        std::string welcome_msg = string(res[0][0]);
                        Send(welcome_msg);
                    }
                    else {
                        Send("Welcome TEST\n");
                    }
                }
                query.reset();
            }catch(const mysqlpp::Exception& err){
                cout<<"WELCOME - ExceptionError - "<<err.what()<<endl;
                query.reset();
            }
            conn.disconnect();
        }
    }
    else
    if (cmd == "EXIT")
    {
        Send("BYE\n");
        SetCloseAndDelete();
    }
    else
    if (cmd == "VERSION") {
        std::string msg;
        msg += "TTPSPServer"; msg += "0.11.4"; msg += "\n";
        Send(msg);
    } else
    {
        Send("NOTCOMMAND\n");
    }
}
